package com.howells.time.module.sendvideo.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.howells.time.R;
import com.howells.time.base.activity.BaseActivity;
import com.howells.time.base.utils.FileUtils;
import com.howells.time.base.utils.StatusBarUtil;
import com.howells.time.base.utils.ToastShow;
import com.howells.time.module.UIHelper;
import com.howells.time.module.sendvideo.model.Mode;
import com.howells.time.module.sendvideo.presenter.SendVideoPresenter;
import com.howells.time.module.sendvideo.presenter.SendVideoPresenterImp;
import com.yqritc.scalablevideoview.ScalableVideoView;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 播放视频页面
 *
 * @author Martin
 */
public class SendVideoActivity extends BaseActivity implements SendVideoView{

    public static final String TAG = "SendVideoActivity";

    public static final String KEY_FILE_PATH = "file_path";

    private String filePath;

    private ScalableVideoView mScalableVideoView;
    private ImageView mPlayImageView;
    private ImageView mThumbnailImageView;
    private RelativeLayout relativeLayout;

    private Intent intent;
    private SendVideoPresenter sendVideoPresenter;
    public List<Mode> selectmode;
    private int selectid=0;
    private String longitudelatitude="";
    private RadioButton isPrivate;
    private long timestamp;
    private int MaxDay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        filePath = getIntent().getStringExtra(KEY_FILE_PATH);
        Log.d(TAG, filePath);
        if (TextUtils.isEmpty(filePath)) {
            Toast.makeText(this, "视频路径错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        setContentView(R.layout.activity_send_video);
        mScalableVideoView = (ScalableVideoView) findViewById(R.id.video_view);
        try {
            // 这个调用是为了初始化mediaplayer并让它能及时和surface绑定
            if (mScalableVideoView != null) {
                mScalableVideoView.setDataSource(filePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        isPrivate= (RadioButton) findViewById(R.id.radioButton);
        mPlayImageView = (ImageView) findViewById(R.id.playImageView);

        mThumbnailImageView = (ImageView) findViewById(R.id.thumbnailImageView);
        mThumbnailImageView.setImageBitmap(getVideoThumbnail(filePath));
        sendVideoPresenter=new SendVideoPresenterImp(this);
        sendVideoPresenter.getMode();
        intent=getIntent();
        relativeLayout= (RelativeLayout) findViewById(R.id.selected_date);
        if (relativeLayout != null) {
            relativeLayout.setEnabled(false);
        }

        StatusBarUtil.setColor(this,0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mScalableVideoView.stop();
        mPlayImageView.setVisibility(View.VISIBLE);
        mThumbnailImageView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1001&&requestCode==10001){
            selectid=data.getIntExtra("id",0);
            TextView modename= (TextView) findViewById(R.id.selected_mode);
            assert modename != null;
            modename.setText(data.getStringExtra("modenmae"));
            MaxDay=data.getIntExtra("maxday",0);
         //   if(MaxDay>0){
                relativeLayout.setEnabled(true);
        //    }
        }
        if(resultCode==1002&&requestCode==10002) {
            TextView addressname= (TextView) findViewById(R.id.selected_address);
            if (addressname != null) {
                addressname.setText(data.getStringExtra("address"));
            }
            longitudelatitude=data.getStringExtra("longitude")+","+data.getStringExtra("latitude");
        }
        if(resultCode==1003&&requestCode==10003){
            TextView time= (TextView) findViewById(R.id.selected_date_text2);
            if (time != null) {
                time.setText(data.getStringExtra("year")+"-"+data.getStringExtra("month")+"-"+data.getStringExtra("day"));
            }
            timestamp=data.getIntExtra("timestamp",0);
        }
    }

    /**
     * 获取视频缩略图（这里获取第一帧）
     * @param filePath
     * @return
     */
    public Bitmap getVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(TimeUnit.MILLISECONDS.toMicros(1));
        }
        catch(IllegalArgumentException e) {
            e.printStackTrace();
        }
        finally {
            try {
                retriever.release();
            }
            catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_view:
                mScalableVideoView.stop();
                mPlayImageView.setVisibility(View.VISIBLE);
                mThumbnailImageView.setVisibility(View.VISIBLE);
                break;
            case R.id.playImageView:
                try {
                    mScalableVideoView.setDataSource(filePath);
                    mScalableVideoView.setLooping(true);
                    mScalableVideoView.prepare();
                    mScalableVideoView.start();
                    mPlayImageView.setVisibility(View.GONE);
                    mThumbnailImageView.setVisibility(View.GONE);
                } catch (IOException e) {
                    Log.e(TAG, e.getLocalizedMessage());
                    Toast.makeText(this, "播放视频异常", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.act_send_voide:
                uploadata();
                break;
            case R.id.select_address:
                UIHelper.jumpSelectAddress(this,getIntent());
                break;
            case R.id.select_mode:
                if(selectmode==null) {
                    ToastShow.ToastShort(this,"模式请求异常");
                    return;
                }
                Bundle bundle=new Bundle();
                bundle.putSerializable("listmode", (Serializable) selectmode);
                intent.putExtras(bundle);
                UIHelper.jumpSelectMode(this, intent);
                break;
            case R.id.select_mode_back:
                finish();
                break;
            case R.id.relativeLayout_ispriavete:
                isPrivate.setChecked(!isPrivate.isChecked());
                break;
            case R.id.selected_date:
                intent.putExtra("maxday",MaxDay);
                UIHelper.jumpSelectDate(this,intent);
                break;
        }
    }

    private void uploadata(){
        if(longitudelatitude.equals("")){
            ToastShow.ToastShort(this,"请选择地理位置");
            return;
        }
        Bitmap pic=getVideoThumbnail(filePath);
        String picpath= FileUtils.saveFile("pic.png", pic);
        Map<String,Object> info=new HashMap<>();
        info.put("type",Integer.toString(selectid));
        info.put("set_time",timestamp);
        info.put("isPrivate",isPrivate.isChecked()==true?1:0);
        info.put("placeXY",longitudelatitude);
        info.put("isWarn","1");
        sendVideoPresenter.uploadvideo(filePath,picpath,info);
    }

    @Override
    public void sendsuccess() {
        ToastShow.ToastShort(this,"发送成功");
        finish();
    }

    @Override
    public void selectmode(Object mode) {
        List<Mode> list= JSON.parseObject(mode.toString(),List.class);
        selectmode=new ArrayList<>();
        for(Object o:list){
            selectmode.add(JSONObject.toJavaObject((JSON) o,Mode.class));
        }
    }

}
